import React, { PureComponent as Component } from 'react';
import {  Table, Button, DatePicker, message } from 'antd';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import axios from 'axios';
import { getProject } from '../../../reducer/modules/dubboProject';
import { getTxtAction } from '../../../reducer/modules/dubboInterface';
const moment = require('moment');
const assert = require('assert');
const limit = 20;

@connect(
  state => {
    return {
      projectMsg: state.project.currProject
    };
  },
  {
    getProject,
    getTxtAction
  }
)
@withRouter
class ProjectExport extends Component {
  constructor(props) {
    super(props);
   this.state = {
     data: [],
     list: [],
     total: 0,
     current: 1,
     totalsize: 0,
     time: '',
     date: '',
     methodIds: []
   };
  }
  static propTypes = {
   getProject: PropTypes.func,
   getTxtAction: PropTypes.func,
   match: PropTypes.object
  };

  getMethodList() {
    const id = this.props.match.params.id;
    axios.get('/api/dubbomethod/listexport?page=' + this.state.current + '&limit=' + limit+'&projectid='+id).then(res => {
      let result = res.data;

      if (result.errcode === 0) {
        let temp = result.data.list;
        let total = result.data.total;
        let list = [];
        for(let i=0; i<temp.length; i++){
          if(temp[i].ischl === 1){
            list.push(temp[i]);
          }
        }
        
        this.setState({
          data: list,
          list: list,
          total: total
        });
      }
    });
  }

  export = () => {
    // try{
      let ids = this.state.methodIds;
      let pid = this.props.match.params.id;
      if (ids.length === 0){
        message.error("请选择要导出的方法！")
      } else {
        this.props.getTxtAction(ids, pid).then(
          res => {
            try{
              if (res.payload.data.errcode === 0) {
                let result_interface = res.payload.data.data.interface;
                let result_method = res.payload.data.data.method;
                let user_interface = res.payload.data.data.user_1;
                let user_method = res.payload.data.data.user_2;
                let project_name = res.payload.data.data.name;
                let project_group = res.payload.data.data.group;
                assert(!(project_name === undefined || project_name === ''), '项目名称为空！');
                assert(!(project_group === undefined || project_group === ''), '项目分组为空！');
                let date = this.state.date;
                let service
                let serviceMap = [];
                let route
                let routeMap = [];
                for(let m=0; m<result_interface.length; m++){
                  let a = result_interface[m];
                  assert(!(a.classname === undefined || a.classname === ''), '接口类名为空！');
                  assert(!(user_interface[m].cuser === undefined || user_interface[m].cuser === ''), '接口创建人为空！');
                  assert(!(user_interface[m].euser === undefined || user_interface[m].euser === ''), '接口最后修改人为空！');
                  assert(!(a.ctime === undefined || a.ctime === ''), '接口创建时间为空！');
                  assert(!(a.etime === undefined || a.etime === ''), '接口最后修改时间为空！');
                  let name = a.classname.split('.');
                  let cuser = user_interface[m].cuser;
                  let euser = user_interface[m].euser;
                  let ctime = moment(a.ctime * 1000).format('YYYY-MM-DD HH:mm:ss');
                  let etime = moment(a.etime * 1000).format('YYYY-MM-DD HH:mm:ss');
                  service = 'INSERT INTO chl_service_info( service_id, service_en_name, service_cn_name, service_inf, service_version, service_status, service_group, time_out, wait_time, service_memo, crt_time, last_upd_time, submit_opr_id, last_upd_id) ';
                  let serviceArr = [a._id.toString(), name[name.length-1], a.cname, a.classname, '1.0.0', '00', project_group, '30000', '1000', a.desc, ctime, etime, cuser, euser];
                  serviceArr = JSON.stringify(serviceArr);
                  serviceArr = serviceArr.replace(/\[/g, '(');
                  serviceArr = serviceArr.replace(/\]/g, ')');
                  serviceArr = serviceArr.replace(/\"/g, '\'');
                  service += ( 'VALUES' + serviceArr );
                  serviceMap.push(service);
                }
    
                for(let n=0; n<result_method.length; n++){
                  let b = result_method[n]
                  assert(!(user_method[n].cuser === undefined || user_method[n].cuser === ''), '方法创建人为空！');
                  assert(!(user_method[n].euser === undefined || user_method[n].euser === ''), '方法最后修改人为空！');
                  assert(!(b.ctime === undefined || b.ctime === ''), '方法创建时间为空！');
                  assert(!(b.etime === undefined || b.etime === ''), '方法最后修改时间为空！');
                  let cuser_1 = user_method[n].cuser;
                  let euser_1 = user_method[n].euser;
                  let ctime_1 = moment(b.ctime * 1000).format('YYYY-MM-DD HH:mm:ss');
                  let etime_1 = moment(b.etime * 1000).format('YYYY-MM-DD HH:mm:ss');
                  if (b.ischl === 1) {
                    route = 'INSERT INTO chl_service_info( txn_id, txn_no, service_id, txn_name, txn_method, txn_method_input, txn_memo, crt_time, last_upd_time, submit_opr_id, last_upd_id, sys_id ) ';
                    assert(!(b.chltype === undefined || b.chltype === ''), '方法渠道号为空！');
                    assert(!(b.infid === undefined || b.infid === ''), '方法所属接口号为空！');
                    assert(!(b.cname === undefined || b.cname === ''), '方法名称为空！');
                    assert(!(b.mname === undefined || b.mname === ''), '方法名为空！');
                    assert(!(b.inname === undefined || b.inname === ''), '请求类名为空！');
                    // assert(!(b.desc === "" || b.desc === undefined ), '方法描述为空！');
                    let routeArr = [b._id.toString(), b.chltype, b.infid.toString(), b.cname, b.mname, b.inname, b.desc, ctime_1, etime_1, cuser_1, euser_1, 'hjpt'];
                    routeArr = JSON.stringify(routeArr);
                    routeArr = routeArr.replace(/\[/g, '(');
                    routeArr = routeArr.replace(/\]/g, ')');
                    routeArr = routeArr.replace(/\"/g, '\'');
                    route += ( 'VALUES' + routeArr );
                    routeMap.push(route);
                  }
                }
    
                serviceMap = JSON.stringify(serviceMap, null, 1);
                serviceMap = serviceMap.replace(/\[/g, '');
                serviceMap = serviceMap.replace(/\]/g, '');
                serviceMap = serviceMap.replace(/\"/g, '');
                routeMap = JSON.stringify(routeMap, null, 1);
                routeMap = routeMap.replace(/\[/g, '');
                routeMap = routeMap.replace(/\]/g, '');
                routeMap = routeMap.replace(/\"/g, '');
    
                let uri_1 = 'data:text;charset=utf-8,\ufeff' + encodeURIComponent(serviceMap);
                let uri_2 = 'data:text;charset=utf-8,\ufeff' + encodeURIComponent(routeMap);
                let name_1 = 'chl_interface_';
                let name_2 ='chl_method_';
                if (date === ''){
                  name_1 += (project_name + '.sql');
                  name_2 += (project_name + '.sql');
                } else{
                  name_1 += (project_name + '_' + date + '.sql');
                  name_2 += (project_name + '_' + date + '.sql');
                }
                let link_1 = document.createElement("a");
                let link_2 = document.createElement("a");
                link_1.href = uri_1;
                link_2.href = uri_2;
                link_1.download = name_1;
                link_2.download = name_2;
                document.body.appendChild(link_1);
                document.body.appendChild(link_2);
                link_1.click();
                link_2.click();
                document.body.removeChild(link_1);
                document.body.removeChild(link_2);
              }
            } catch (e) {
              message.error(e.message);
            }
          }
        );
      }
    // } catch(e) {
    //   // jctest
    //   console.log(e)
    //   console.log(e.message)
    //   message.error(e.message);
    // }
  }
  
  onChange = (date, dateString) => {
    if (dateString === ''){
      this.setState({
        list: this.state.data
      })
    } else {
      let list = [];
      let data = this.state.data;
      for(let i=0; i<data.length; i++){
        if (data[i].onlinedate === dateString){
          list.push(data[i])
        }
      }
      this.setState({
        time: date,
        date: dateString,
        list: list
      })
    }
  }

  changePage = current => {
    this.setState(
      {
        current: current
      },
      this.getMethodList
    );
  };

  async componentWillMount(){
    this.getMethodList();
  }

  render(){
    const columns = [
      {
        title: '接口名称',
        dataIndex: 'infname',
        key: 'infname'
      },
      {
        title: '接口中文名称',
        dataIndex: 'infcname',
        key: 'infcname'
      },
      {
        title: '方法名称',
        dataIndex: 'mname',
        key: 'mname'
      },
      {
        title: '方法中文名称',
        dataIndex: 'cname',
        key: 'cname'
      },
      {
        title: '上线时间',
        dataIndex: 'onlinedate',
        key: 'onlinedate'
      },
      {
        title: '测试状态',
        dataIndex: 'status',
        key: 'status'
      }
    ];
    const pageConfig = {
      total: this.state.total,
      pageSize: limit,
      current: this.state.current,
      onChange: this.changePage
    };
    const rowSelection = {
      onChange: (selectedRowKeys) => {
        this.setState({
          methodIds: selectedRowKeys,
          totalsize: selectedRowKeys.length
        })
      }
    };
    return (
      <section className="user-table">
        <div style={{margin:'24px 24px 0',backgroundColor:'#ffffff',padding:'24px'}}>
          <div className="user-search-wrapper" style={{marginBottom:"10px"}}>
            <div style={{textAlign:'right'}}>
              <strong style={{ marginRight: '10px' }}>导出渠道方法总数：{this.state.totalsize}</strong>
              <strong style={{ marginRight: '10px' }}>渠道方法总数：{this.state.list.length}</strong>
              <DatePicker onChange={this.onChange} placeholder="请选择上线时间" style={{ marginRight: '10px' }} />
              <Button type="primary" onClick={ () => {this.export()} }>导出渠道数据</Button>
            </div>
          </div>
          <Table
              dataSource={this.state.list}
              columns={columns}
              pagination={pageConfig}
              bordered={true}
              rowKey={record => record.id}
              rowSelection={rowSelection}
          />
        </div>
      </section>);
  }
}

export default ProjectExport;
